package com.meida.msg.provider.service.impl;

import com.alibaba.fastjson.util.TypeUtils;
import com.meida.common.base.client.BasePushClient;
import com.meida.common.base.service.BaseAdminUserService;
import com.meida.common.constants.CommonConstants;
import com.meida.common.mybatis.base.service.impl.BaseServiceImpl;
import com.meida.common.base.entity.EntityMap;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaDelete;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.mybatis.query.CriteriaSave;
import com.meida.common.mybatis.query.CriteriaUpdate;
import com.meida.common.security.OpenHelper;
import com.meida.common.utils.DateUtils;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.utils.StringUtils;
import com.meida.module.admin.client.entity.BaseUser;
import com.meida.module.admin.provider.mapper.BaseUserCompanyMapper;
import com.meida.module.admin.provider.service.BaseUserService;
import com.meida.msg.client.entity.MsgContent;
import com.meida.msg.client.entity.MsgType;
import com.meida.msg.provider.mapper.MsgContentMapper;
import com.meida.msg.provider.service.MsgContentService;
import com.meida.msg.provider.service.MsgReceiveService;
import com.meida.msg.provider.websocket.WebSocketServerEndpoint;
import javassist.bytecode.analysis.Type;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 消息表接口实现类
 *
 * @author flyme
 * @date 2020-02-26
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class MsgContentServiceImpl extends BaseServiceImpl<MsgContentMapper, MsgContent> implements MsgContentService {

    @Resource
    private MsgContentMapper msgContentMapper;

    @Autowired(required = false)
    private BasePushClient basePushClient;

    @Resource
    private MsgReceiveService msgReceiveService;

    @Autowired
    private BaseUserService baseUserService;

    @Autowired
    private WebSocketServerEndpoint webSocketServerEndpoint;

    @Autowired
    private BaseUserCompanyMapper baseUserCompanyMapper;

    @Override
    public ResultBody beforeEdit(CriteriaUpdate<MsgContent> cu, MsgContent msgContent, EntityMap extra) {
        String msgSummary = StringUtils.stripXss(msgContent.getMsgContent()).trim();
        if (FlymeUtils.isNotEmpty(msgSummary) && msgSummary.length() > 20) {
            msgSummary = msgSummary.substring(0, 18);
        }
        msgContent.setMsgSummary(msgSummary);
        return super.beforeEdit(cu, msgContent, extra);
    }

    @Override
    public ResultBody beforeAdd(CriteriaSave cs, MsgContent content, EntityMap extra) {
        content.setDeleted(CommonConstants.DEL_NO);
        content.setMsgState(CommonConstants.DISABLED);
        String msgSummary = StringUtils.stripXss(content.getMsgContent()).trim();
        if (FlymeUtils.isNotEmpty(msgSummary) && msgSummary.length() > 20) {
            msgSummary = msgSummary.substring(0, 18);
        }
        content.setSendTime(DateUtils.getNowDate());
        content.setMsgSummary(msgSummary);
        return ResultBody.ok();
    }

    @Override
    public ResultBody afterAdd(CriteriaSave cs, MsgContent msgContent, EntityMap extra) {
        Boolean pushState = msgContent.getPushState();
        if (FlymeUtils.isNotEmpty(basePushClient) && pushState) {
            Integer deviceType = FlymeUtils.getInteger(msgContent.getPushDeviceType(), 0);
            String title = msgContent.getMsgTitle();
            basePushClient.getService("name1").sendByDeviceType(deviceType, "系统通知", title, title, null);
        }
        return super.afterAdd(cs, msgContent, extra);
    }


    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public ResultBody beforePageList(CriteriaQuery<MsgContent> cq, MsgContent content, EntityMap requestMap) {
        cq.addSelect(MsgType.class, "typeName");
        cq.addSelect(MsgContent.class, "*");
        cq.and(i -> i.eq("typeCode", "SystemMsg").or(j -> j.eq("typeCode", "SystemMaintenance")));
        cq.orderByDesc("content.createTime");
        cq.createJoin(MsgType.class);
        return ResultBody.ok();
    }

    @Override
    public ResultBody afterDelete(CriteriaDelete cd, Long[] ids) {
        msgReceiveService.deleteByMsgId(ids);
        return super.afterDelete(cd, ids);
    }

    @Override
    public List<MsgContent> selectNotReceiveByUserId(EntityMap params) {
        return msgContentMapper.selectNotReceiveByUserId(params);
    }

    @Override
    public ResultBody sendMessage(Map params) {
        Long msgId = TypeUtils.castToLong(params.get("msgId"));
        MsgContent msgContent = getById(msgId);
        msgContent.setMsgState(1);
        boolean b = updateById(msgContent);
        if (b) {
            Long companyId=OpenHelper.getCompanyId();
            List<Long> userIds = baseUserCompanyMapper.selectUserIdByCompanyId(companyId);
            webSocketServerEndpoint.sendMessage(msgContent, userIds, 1);
        }
        return ResultBody.ok("发布成功");
    }


}
